/*
 * @lc app=leetcode id=23 lang=cpp
 *
 * [23] Merge k Sorted Lists
 */
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:

    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {

        if (!l1 || !l2) {
            return l1 ? l1 : l2;
        }

        ListNode *head = NULL, *node = NULL;
        ListNode *n1 = l1, *n2 = l2;
        while (n1 && n2) {
            if (n1->val < n2->val) {
                if (!head) {
                    head = n1;
                    node = head;
                } else {
                    node->next = n1;
                    node = node->next;
                }
                n1 = n1->next;
            } else {
                if (!head) {
                    head = n2;
                    node = head;
                } else {
                    node->next = n2;
                    node = node->next;
                }
                n2 = n2->next;
            }
        }

        if (n1) {
            node->next = n1;
        }
        if (n2) {
            node->next = n2;
        }
        return head;
    }

    ListNode *mergeKLists(vector<ListNode*>& lists, int st, int ed) {
        if (st > ed) {
            return NULL;
        } else if (st == ed) {
            return lists[st];
        } else if (st + 1 == ed) {
            return mergeTwoLists(lists[st], lists[ed]);
        } else {
            int mid = (st+ed)/2;
            return mergeTwoLists(mergeKLists(lists, st, mid), mergeKLists(lists, mid+1, ed));
        }
    }

    ListNode* mergeKLists(vector<ListNode*>& lists) {

        int len = lists.size();
        if (len < 1) {
            return NULL;
        }
        
        return mergeKLists(lists, 0, len-1);
    }
};

